/*
Copyright 2010-2011 CumulusCloud
http://cumuluscloud.cc

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package cumulusCloud.caching;

import java.util.Collection;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

public class ConcurrentHashMapAmountCache<K, V> implements Map<K, V> {
	private Map<K, V> items = new ConcurrentHashMap<K, V>();
	private Queue<K> order = new ConcurrentLinkedQueue<K>();
	private int maxItems;

	public ConcurrentHashMapAmountCache(int maxItems) {
		this.maxItems = maxItems;
	}
	
	private void cleanIfNeeded() {
		int amountToRemove = items.size() - maxItems;
		if (amountToRemove <= 0) return;
		
		for (int i=0; i<amountToRemove; ++i) {
			K key = order.poll();
			items.remove(key);
		}
	}

	@Override
	public void clear() {
		items.clear();
		order.clear();
	}

	@Override
	public boolean containsKey(Object key) {
		return items.containsKey(key);
	}

	@Override
	public boolean containsValue(Object value) {
		return items.containsValue(value);
	}

	@Override
	public Set<java.util.Map.Entry<K, V>> entrySet() {
		return items.entrySet();
	}

	@Override
	public V get(Object key) {
		return items.get(key);
	}

	@Override
	public boolean isEmpty() {
		return items.isEmpty();
	}

	@Override
	public Set<K> keySet() {
		return items.keySet();
	}

	private void moveToTop(K key) {
		order.remove(key);
		order.add(key);
	}

	@Override
	public V put(K key, V value) {
		V result = items.put(key, value);
		if (result != null) {
			moveToTop(key);
		} else {
			order.add(key);
			cleanIfNeeded();
		}
		
		return result;
	}

	@Override
	public void putAll(Map<? extends K, ? extends V> m) {
		items.putAll(m);
		
		for (K next: m.keySet()) {
			if (order.contains(next)) {
				moveToTop(next);
			} else {
				order.add(next);
			}
		}
		
		cleanIfNeeded();
	}

	@Override
	public V remove(Object key) {
		order.remove(key);
		return items.remove(key);
	}

	@Override
	public int size() {
		return items.size();
	}

	@Override
	public Collection<V> values() {
		return items.values();
	}
}
